#include "POSIX_SharedMemory.hpp"
#include <fcntl.h>
#include <sys/stat.h>
#include <stdexcept>
#include <unistd.h>

POSIX_SharedMemory::POSIX_SharedMemory(const std::string & name,long size)
{
  fd=shm_open(name.c_str(),O_EXCL | O_RDWR,S_IRUSR | S_IWUSR);
  if(fd==-1)
    throw std::runtime_error("无法打开共享内存");
  memory=(char*)mmap(nullptr,size,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
  if(memory==MAP_FAILED)
    throw std::runtime_error("无法将共享内存映射到程序");
}

POSIX_SharedMemory::~POSIX_SharedMemory()
{
  close(fd);
}

char* POSIX_SharedMemory::GetMemory()
{
  return memory;
}
